<?
/**
 * VoiceOne Settings/Rules/incoming/edit-rule
 *
 * Frontend to provide access to the rules system in voiceone.
 * @package voiceone
 * @subpackage  settings_rules
 */
  include ("../../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");
 	sajax_init();
  
  //=================== XAJAX ==================
  function callerCase($callerType, $callerid){
    global $asterisk, $cwlang, $relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    $html="";
    switch ($callerType) {
        case CALLER_ALL:  
          $html.=T_("all caller with no restriction on caller id");
          $objResponse->addAssign("callerdesc","innerHTML", $html);
          $objResponse->addAssign("callerset","innerHTML", "");
        break;
        case CALLER_ANONYMOUS:
          $html.=T_("all caller that don't show caller id");
          $objResponse->addAssign("callerdesc","innerHTML", $html);
          $objResponse->addAssign("callerset","innerHTML", "");
        break;
        case CALLER_ID:
          $html.=" <dt class=\"required\"><label for=\"callerid\">".T_("Phone number").":</label></dt> ";
          $html.=" <dd><input type=\"textfield\"  id=\"callerid\" name=\"callerid\" value=\"".$callerid."\"/>&nbsp;<span>".T_("set the caller id (i.e. <strong>3401234567</strong>)")."<span></dd> ";
          $objResponse->addAssign("callerdesc","innerHTML", "");
          $objResponse->addAssign("callerset","innerHTML", $html);
        break;
        case CALLER_CLASS:
        case CALLER_GROUP:
          //group
          $icon_group="<img src=\"$relBasePath/public/img/icon_numbers.gif\" alt=\"group of phonenumbers\" />";
          $ret=$asterisk->getGroup(0,GROUP_OF_PHONENUMBER);
          $alreadyChecked=false;
          if ((is_array($ret))&&($ret!="")){
            $almostOneGroup=true;
            $count=0;
            $html_meta="";
            $html_gpr="";
            foreach($ret as $group){
              $grpid=$group["id"];
              $grpmeta=$group["metagroup"];
              $grpname=str_replace("-"," ",str_replace("_","",$group["name"]));
              if($callerid==$grpid){
                $checked="checked=\"checked\"";
                $alreadyChecked=true; 
              }else $checked="";
              if($grpmeta){
                if($alreadyChecked===false){ $checked="checked=\"checked\"";$alreadyChecked=true; }
                $grpname="<strong>[".strtoupper($grpname)."]</strong>";
                $html_meta.="<td width=\"50%\"><input type=\"radio\" id=\"callerid\" name=\"callerid\" value=\"".$grpid."\" $checked /> $icon_group ".$grpname."<input type=\"hidden\" id=\"groupMeta\" name=\"groupMeta\" value=\"".$grpid."\" /></td>";
              }else{ 
                $html_gpr.="<td width=\"50%\"><input type=\"radio\" id=\"callerid\" name=\"callerid\" value=\"".$grpid."\" $checked /> $icon_group ".$grpname."<input type=\"hidden\" id=\"groupArr[".$count."]\" name=\"groupArr[".$count."]\" value=\"".$grpid."\" /></td>";
                if (($count++)%2==1) $html_gpr.="</tr><tr>\n";
              }
            }
            $html="<div><strong>All:</strong><table><tr>".$html_meta."</tr></table></div>";
            $html.="<div><strong>Group:</strong><table><tr>".$html_gpr."</tr></table></div>";
          }else $almostOneGroup=false;
          //class
          $icon_group="<img src=\"$relBasePath/public/img/icon_number.gif\" alt=\"class of phonenumbers\" />";
          $ret=$asterisk->getPhoneNumber("");
          if((is_array($ret))&&($ret!="")){
            $almostOneClass=true;
            $count=0;
            $html_class.="<table><tr>";
            foreach($ret as $number){
              if($alreadyChecked===false){ $checked="checked=\"checked\"";$alreadyChecked=true; }
              else if($callerid==$number["id"]) $checked="checked=\"checked\""; else $checked="";
              $html_class.="<td width=\"50%\"><input type=\"radio\" id=\"callerid\" name=\"callerid\" value=\"".$number["id"]."\" $checked /> $icon_group ".$number["name"]."<input type=\"hidden\" id=\"entityArr[".$count."]\" name=\"entityArr[".$count."]\" value=\"".$number["id"]."\" /></td>";
              if (($count++)%2==1) $html_class.="</tr><tr>\n";
            }
            $html_class.="</tr></table>";
            $html.="<div><strong>Entity:</strong>".$html_class."</div>";
            $objResponse->addAssign("callerdesc","innerHTML", T_("unknown Caller-Type 4"));
            $objResponse->addAssign("callerset","innerHTML", $html);
          }else $almostOneClass=false;
          //output
          if(($almostOneGroup===false)&&($almostOneClass===false)){
            $objResponse->addAssign("callerdesc","innerHTML", T_("no Dial Patterns are defined"));
            $objResponse->addAssign("callerset","innerHTML", "");
          }else{
            $objResponse->addAssign("callerdesc","innerHTML", T_("select Dial Pattern"));
            $objResponse->addAssign("callerset","innerHTML", $html);
          }
        break;
        default:
          $objResponse->addAssign("callerdesc","innerHTML", "");
          $objResponse->addAssign("callerset","innerHTML", "");  
        break;
    }
    return $objResponse->getXML();
  }
  function roll(){
    global $relBasePath,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $html=" <img src=\"".$relBasePath."public/img/ico-progress.gif"."\" alt=\"loading\" /><span>".T_("loading")."</span>";
    $objResponse->addAssign("loading","innerHTML",$html);
    // Return the xajaxResponse object
    return $objResponse->getXML(); 
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Extract form's params
    $callerType=$formData["callertype"];
    $callerid=$formData["callerid"];
    $macro=$formData["macro"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">&nbsp;&nbsp;";
    // Check Caller ID ((not null))
    $callerErr=false;
    if(($callerType==CALLER_GROUP)&&((!isset($formData["callerid"]))||($callerid==""))) { 
      //caller id cannot be null
      $errOut[]= T_("Dial Pattern cannot be null");
      $objResponse->addAssign("callerErr","innerHTML",$imgErr);
      $callerErr=true;  
    }
    if($callerErr===false) $objResponse->addAssign("callerErr","innerHTML","");
    // Check Macro ((not null))
    $macroErr=false;
    if((!isset($formData["macro"]))||($macro=="")) { 
      //trunk list cannot be null
      $errOut[]= T_("Macro cannot be null");
      $objResponse->addAssign("macroErr","innerHTML",$imgErr);
      $macroErr=true;  
    }
    if($macroErr===false) $objResponse->addAssign("macroErr","innerHTML","");
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML",""); 
      $objResponse->addScript(" document.getElementById('mainform').submit(); ");
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();  
  }
  $xajax = new xajax();
  $xajax->registerFunction("callerCase");
  $xajax->registerFunction("roll");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();
  
  //================== POST ==================
  if (count($_POST)>0) {
    if(($_POST["callertype"]==CALLER_GROUP)&&($_POST["callerid"]!="")){
      if(($_POST["groupMeta"]!="")&&($_POST["callerid"]==$_POST["groupMeta"])) $_POST["callertype"]=CALLER_GROUP;
      else if((is_array($_POST["groupArr"]))&&(in_array($_POST["callerid"],$_POST["groupArr"]))) $_POST["callertype"]=CALLER_GROUP;
      else if((is_array($_POST["entityArr"]))&&(in_array($_POST["callerid"],$_POST["entityArr"]))) $_POST["callertype"]=CALLER_CLASS;
    }
    $entry=Array(
      "id"  => $_POST["id"],
      "rule" => $_POST["rule"],
      "priority" => $_POST["priority"],
      "timesegment" => $_POST["timesegment"], 
      "callertype" => $_POST["callertype"],
      "callerid" => $_POST["callerid"], 
      "from_channel" => $_POST["trunk"], 
      "from_number" => $_POST["number"], 
      "macro" => $_POST["macro"], 
      "duration" => $_POST["duration"] 
    );
    //merge the parameter
    if (is_array($_POST["macro_param"]))
    foreach ($_POST["macro_param"] as $k=>$v) $p.="$k=$v|";
    $p=substr($p,0,-1);
    $entry["parameter"]=$p;
    //save the group informations
    $ret=$asterisk->putIncomingRule($entry);
    if ($ret>0) {
      $alert="<div class=\"AlertGood\">".T_("Rule created")."</div>";
      $_GET["id"]=$ret;
    } else $alert="<div class=\"AlertBad\">".T_("Error: Rule not created")."</div>";
    goToMainPage($alert);
  }
  
  //================ PAGE LOGIC ================
  //if modify, read the group informations
  if (isset($_GET["id"])) {
    $ret=$asterisk->getIncomingRule($_GET["id"]);
    if ($err=$asterisk->getError()) die("Error: $err");
    $id=$ret[0]["id"];
    $rule=$ret[0]["rule"];
    $priority=$ret[0]["priority"];
    $timesegment=$ret[0]["timesegment"];
    $callertype=$ret[0]["callertype"];  
    $callerid=$ret[0]["callerid"];  
    $trunk=$ret[0]["from_channel"]; 
    $number=implode("|",$ret[0]["from_number"]);  
    $macro=$ret[0]["macro"];  
    $parameter=$ret[0]["parameter"];  
    $duration=$ret[0]["duration"]; 
  }  
  //Get the time segment available
  $tsHtml.="<option value=\"0\">[".T_("Any time")."]</option>\n";
  $ret=$asterisk->getTimeSegment(0);
  if ($err=$asterisk->getError()) die("Error: $err");
  if (is_array($ret)) 
  foreach ($ret as $ts) {
    $id=$ts["id"];
    $name=$ts["name"];
    if ($id==$timesegment) $selected=" selected=\"selected\" ";
    else $selected="";
    $tsHtml.="<option value=\"$id\" $selected>$name</option>\n";
  }
  //Define callerList
  $callerList="";
  $script="";
  if($callertype==CALLER_ALL) {
    $callerList.="<option value=\"".CALLER_ALL."\" selected=\"selected\">[".T_("Any")."]</option>";
    $script="<script> xajax_callerCase('".CALLER_ALL."','".$callerid."'); </script>";
  }else $callerList.="<option value=\"".CALLER_ALL."\" >[".T_("Any")."]</option>";  
  if($callertype==CALLER_ANONYMOUS) {
    $callerList.="<option value=\"".CALLER_ANONYMOUS."\" selected=\"selected\">".T_("Anonymous")."</option>";
    $script="<script> xajax_callerCase('".CALLER_ANONYMOUS."','".$callerid."'); </script>";
  }else $callerList.="<option value=\"".CALLER_ANONYMOUS."\" >".T_("Anonymous")."</option>";
  if($callertype==CALLER_ID) {
    $callerList.="<option value=\"".CALLER_ID."\" selected=\"selected\">".T_("Phone number")."</option>";
    $script="<script> xajax_callerCase('".CALLER_ID."','".$callerid."'); </script>";
  }else $callerList.="<option value=\"".CALLER_ID."\" >".T_("Phone number")."</option>";
  if(($callertype==CALLER_CLASS)||($callertype==CALLER_GROUP)) {
    $callerList.="<option value=\"".CALLER_GROUP."\" selected=\"selected\">".T_("Phone Number Class")."</option>";
    $script="<script> xajax_callerCase('".CALLER_GROUP."','".$callerid."'); </script>";
  }else $callerList.="<option value=\"".CALLER_GROUP."\" >".T_("Phone Number Class")."</option>";
  /*
  if($callertype==CALLER_GROUP) {
    $callerList.="<option value=\"".CALLER_GROUP."\" selected=\"selected\">".T_("Phone Number Group")."</option>";
    $script="<script> xajax_callerCase('".CALLER_GROUP."','".$callerid."'); </script>";
  }else $callerList.="<option value=\"".CALLER_GROUP."\" >".T_("Phone Number Group")."</option>";
  */
  if($script=="") $script="<script> xajax_callerCase('".CALLER_ALL."','".$callerid."'); </script>";
  
  $id=$_REQUEST["id"];
  $rule=$_REQUEST["rule"];  
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/"); 
  ?>
  <?$sel="incoming";include("../../navigation.php");?>
  
  <?=$script?>
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=T_("Incoming rule")?></h1>
    <h3><a href="../" class="admin" ><?=T_("Return without save")?></a></h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?><?if (isset($_GET["id"])) echo "?id=".$_GET["id"];?>" method="post">
      <!-- TIME SEGMENT -->
    	<h2><?=T_("Time segment")?></h2>
      <p class="blockintro"><?=T_("set the time segment")?></p>
      <div class="block">
        <table>
          <tr>
            <td class="required" width="160"><label for="timesegment"><?=T_("Time segment")?>:</label></td>
            <td ><select id="timesegment" name="timesegment" ><?=$tsHtml?></select></td>
          </tr>
        </table>
      </div>
      <!-- CALLER ID -->
      <h2><?=T_("Caller Id")?></h2>
      <p class="blockintro"><?=T_("set the caller id")?></p>
      <div class="block">
        <dl>
          <dt class="required" ><label for="callertype"><?=T_("Caller Id")?>:</label></dt>
          <dd><select id="callertype" name="callertype" onchange="xajax_callerCase(this.options[this.selectedIndex].value,'<?=$callerid?>');" ><?=$callerList?></select>&nbsp;&nbsp;<span id="callerErr"></span><span id="callerdesc"></span></dd>
          <div id="callerset"></div>  
        </dl>
      </div>
      <!-- TRUNKS -->
      <?echo listTrunk($js, $trunk, $number);?>      
      <!-- MACRO -->
      <?echo listMacro($js, $macro, $parameter);?>      
      <!-- STOP or CONTINUE -->
      <input type="hidden" id="duration" name="duration" value="0" />
      <!--
    	<h2><?=T_("Stop")?></h2>
      <p class="blockintro"><?=T_("Stop executing the next rule after this")?></p>
      <div class="block">
        <table>
          <tr>
            <td class="required" width="160"><label for="duration"><?=T_("Action to do")?>:</label></td>
            <td >
              <input type="radio" id="duration" name="duration" value="0" <?if ($duration=="0" or $duration=="") echo "checked=\"checked\"";?>/>
              <?=T_("Stop or")?>
              <input type="radio" id="duration" name="duration" value="1" <?if ($duration=="1") echo "checked=\"checked\"";?>/>
              <?=T_("Continue")?>
            </td>
          </tr>
        </table>
      </div>
      -->
      <!-- INPUT BUTTONS -->
      <?=$numHidden?>      
      <div class="action">
        <input type="hidden" name="id" value="<?=$id?>" />
        <input type="hidden" name="rule" value="<?=$rule?>" />
        <input type="hidden" name="priority" value="<?=$priority?>" />
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>  
      <!--
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" />
       -->
      </div>
    </form>
   </div>  
  
  <?
  //show macro content
  if (isset($_GET["id"])) echo "<script>show($show);</script>";
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <h1><?=T_("Edit the Rule")?></h1>
      <p><?=T_("Here you edit your rule")?>
    </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
 	sajax_handle_client_request();
  $smarty->assign("section", "rules");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->assign("ajax", $js);
  $smarty->display('settings.tpl');
?>

